package com.chukun.multi.twophase;


import com.chukun.multi.enums.AlarmType;
import com.chukun.multi.guarded.example.AlarmInfo;
import com.chukun.multi.utils.Debug;

/**
 * @author chukun
 * 报警功能入口
 */
public class AlarmMgr {

    // 创建报警类的单例对象
    private static final AlarmMgr INSTANCE = new AlarmMgr();

    private volatile boolean shutdownRequested = false;

    // 报警线程
    private final AlarmSendingThread alarmSendingThread;

    private AlarmMgr() {
        alarmSendingThread = new AlarmSendingThread();
    }

    /**
     * 返回单例对象
     *
     * @return
     */
    public static AlarmMgr getInstance() {
        return INSTANCE;
    }

    /**
     * 发送报警
     *
     * @param type      报警类型
     * @param id        报警编号
     * @param extraInfo 报警参数
     * @return
     */
    public int sendAlarm(AlarmType type, String id, String extraInfo) {
        Debug.info("trigger alarm " + type + " , " + id + " , " + extraInfo);
        int duplicateSubmissionCount = 0;
        try{
            AlarmInfo alarmInfo = new AlarmInfo(id,type);
            alarmInfo.setExtraInfo(extraInfo);
            duplicateSubmissionCount = alarmSendingThread.sendAlarm(alarmInfo);
        }catch (Throwable t) {
            t.printStackTrace();
        }
        return duplicateSubmissionCount;
    }

    public void init() {
        alarmSendingThread.start();
    }

    public synchronized void shutdown() {
        if (shutdownRequested) {
            throw new IllegalArgumentException("shutdown already requested");
        }
        alarmSendingThread.terminate();
        shutdownRequested = true;
    }

}
